﻿using Common;
using IBLL;
using IDAL;
using Models;
using Models.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BLL
{
    /// <summary>
    /// 商店员工表业务逻辑层--实现
    /// </summary>
    public class StaffInfoBLL : IStaffInfoBLL
    {
        #region 构造函数
        private IStaffInfoDAL _staffInfoDAL;
        private UnmanContexts _dbContext;
        public StaffInfoBLL(
            IStaffInfoDAL staffInfoDAL
            , UnmanContexts dbContext
            )
        {
            _staffInfoDAL = staffInfoDAL;
            _dbContext = dbContext;
        }

        #endregion

        #region 登录方法（Login）
        /// <summary>
        /// 商店登录业务逻辑
        /// </summary>
        /// <param name="account">账号</param>
        /// <param name="password">密码</param>
        /// <param name="msg">返回的消息</param>
        /// <param name="staffName">返回的员工名</param>
        /// <param name="staffId">返回的员工Id</param>
        /// <returns></returns>
        public bool Login(string account, string password, out string msg, out string staffName, out string staffId)
        {
            //把密码加密为MD5
            string newPassword = MD5Helper.GenerateMD5(password);
            //根据账号密码查询商店员工
            StaffInfo staffInfo = _staffInfoDAL.GetStaffInfos().FirstOrDefault(s => s.Account == account && s.PassWord == newPassword);

            staffName = "";
            staffId = "";
            //判断是否存在该用户
            if (staffInfo == null)
            {
                msg = "账号或密码！";
                return false;
            }
            else
            {
                msg = "成功！";
                staffName = staffInfo.StaffName;
                staffId = staffInfo.Id;
                return true;
            }
        }
        #endregion

        #region 查询员工列表的方法（GetStaffInfo）--分页
        /// <summary>
        /// 查询员工列表的接口--分页
        /// </summary>
        /// <param name="page">第几页</param>
        /// <param name="limit">每页几条数据</param>
        /// <param name="account">员工账号</param>
        /// <param name="staffName">员工姓名</param>
        /// <param name="count">数据总量</param>
        /// <returns></returns>
        public List<GetStaffInfoDTO> GetStaffInfo(int page, int limit, string account, string staffName, out int count)
        {
            //linq方法进行链表
            var data = from s in _dbContext.StaffInfo.Where(s => s.IsDalete == false)
                       join d in _dbContext.DepartmentInfo.Where(d => d.IsDalete == false)
                       on s.DepartmentId equals d.Id
                       into tempSD
                       from sd in tempSD.DefaultIfEmpty()
                       select new GetStaffInfoDTO
                       {
                           Id = s.Id,
                           Account = s.Account,
                           StaffName = s.StaffName,
                           PhoneNum = s.PhoneNum,
                           Sex = s.Sex == 0 ? "女" : "男",
                           DepartmentName = sd == null ? "" : sd.DepartmentName,
                           DepartmentId = s.DepartmentId,//把部门的id返回
                           CreateTime = s.CreateTime
                       };
            //员工姓名不为空
            if (!string.IsNullOrWhiteSpace(staffName))
            {
                data = data.Where(s => s.StaffName.Contains(staffName));
            }
            //员工账号
            if (!string.IsNullOrWhiteSpace(account))
            {
                data = data.Where(u => u.Account.Contains(account));
            }
            //求总数
            count = data.Count();
            //分页
            var listPage = data.OrderByDescending(u => u.CreateTime).Skip(limit * (page - 1)).Take(limit).ToList();
            //返回结果
            return listPage;
        }
        #endregion

        #region 查询用户列表的方法(GetUserInfos)


        /// <summary>
        /// 查询用户列表的方法
        /// </summary>      
        /// <returns></returns>
        public List<GetStaffInfoDTO> GetStaffInfos()
        {
            List<GetStaffInfoDTO> userList = _staffInfoDAL.GetEntities()
                                                        .Where(x => x.IsDalete == false)
                                                        .Select(x => new GetStaffInfoDTO
                                                        {
                                                            Id = x.Id,
                                                            Account = x.Account,
                                                            PhoneNum = x.PhoneNum,
                                                            DepartmentId = x.DepartmentId,
                                                            Sex = x.Sex == 1 ? "男" : "女",
                                                            CreateTime = x.CreateTime,
                                                            StaffName = x.StaffName

                                                        })
                                                        .ToList();
            return userList;
        }


        #endregion

        #region 添加员工的方法（CreateStaffInfo）
        /// <summary>
        /// 添加员工的接口
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool CreateStaffInfo(StaffInfo entity, out string msg)
        {
            //先判断这个用户非空信息
            if (string.IsNullOrWhiteSpace(entity.StaffName))
            {
                msg = "员工姓名不能为空！";
                return false;
            }
            if (string.IsNullOrWhiteSpace(entity.PassWord))
            {
                msg = "密码不能为空！";
                return false;
            }
            if (string.IsNullOrWhiteSpace(entity.Account))
            {
                msg = "用户账号不能为空！";
                return false;
            }
            if (string.IsNullOrWhiteSpace(entity.PhoneNum))
            {
                msg = "手机不能为空！";
                return false;
            }
            //判断账号是否重复
            StaffInfo staff = _staffInfoDAL.GetEntities().FirstOrDefault(s => s.Account == entity.Account);
            if (staff != null)
            {
                msg = "员工账号已经存在！";
                return false;
            }
            //赋值Id
            entity.Id = Guid.NewGuid().ToString();
            //时间
            entity.CreateTime = DateTime.Now;
            //加密密码
            entity.PassWord = MD5Helper.GenerateMD5(entity.PassWord);

            //更新到数据库
            bool isSuccess = _staffInfoDAL.CreateEntity(entity);

            //新判断
            msg = isSuccess ? $"添加成功！" : "添加失败";
            return isSuccess;
        }
        #endregion

        #region 更新员工信息的方法（UpdateStaffInfo）
        /// <summary>
        /// 更新员工信息的接口
        /// </summary>
        /// <param name="staffInfo">要更新的实体</param>
        /// <param name="msg">返回的描述信息</param>
        /// <returns></returns>
        public bool UpdateStaffInfo(StaffInfo staffInfo, out string msg)
        {
            #region 非空判断
            //非空判断
            if (string.IsNullOrWhiteSpace(staffInfo.Id))
            {
                msg = "Id不能为空！";
                return false;
            }
            //先判断这个用户非空信息
            if (string.IsNullOrWhiteSpace(staffInfo.StaffName))
            {
                msg = "员工姓名不能为空！";
                return false;
            }
            if (string.IsNullOrWhiteSpace(staffInfo.Account))
            {
                msg = "员工账号不能为空！";
                return false;
            }
            //if (string.IsNullOrWhiteSpace(userInfo.PassWord))
            //{
            //    msg = "用户密码不能为空！";
            //    return false;
            //}
            if (string.IsNullOrWhiteSpace(staffInfo.PhoneNum))
            {
                msg = "手机不能为空！";
                return false;
            }
            #endregion

            //判断这个id是否存在员工
            StaffInfo entity = _staffInfoDAL.GetEntityById(staffInfo.Id);
            if (entity == null)
            {
                msg = "员工id无效";
                return false;
            }
            //先判断是不是跟原来的账号一样,一样表示没有修改
            if (entity.Account != staffInfo.Account)
            {
                //通过账号查询数据库里是否存在相同的账号
                StaffInfo oldStaff = _staffInfoDAL.GetEntities().FirstOrDefault(s => s.Account == staffInfo.Account);
                if (oldStaff != null)
                {
                    msg = "账号已被使用";
                    return false;
                }
            }

            //赋值
            entity.Account = staffInfo.Account;
            entity.StaffName = staffInfo.StaffName;
            entity.PhoneNum = staffInfo.PhoneNum;
            entity.DepartmentId = staffInfo.DepartmentId;
            entity.Sex = staffInfo.Sex;

            //三元表达式
            entity.PassWord = string.IsNullOrWhiteSpace(staffInfo.PassWord) ? entity.PassWord : MD5Helper.GenerateMD5(staffInfo.PassWord);

            //更新到数据库
            bool isOk = _staffInfoDAL.UpdateEntity(entity);
            msg = isOk ? "修改成功" : "修改失败";
            //返回结果
            return isOk;
        }
        #endregion

        #region 员工软删除的方法（DeleteStaffInfo）
        /// <summary>
        /// 员工软删除的接口
        /// </summary>
        /// <param name="id">被删除的员工id</param>
        /// <returns></returns>
        public bool DeleteStaffInfo(string id)
        {
            //根据id查用户是否存在
            StaffInfo staffInfo = _staffInfoDAL.GetEntityById(id);
            if (staffInfo == null)
            {
                return false;
            }
            //修改员工的状态
            staffInfo.IsDalete = true;
            staffInfo.DeleteTime = DateTime.Now;
            //返回结果
            return _staffInfoDAL.UpdateEntity(staffInfo);
        }
        #endregion

        #region 员工批量软删除的方法（DeleteStaffInfo）
        /// <summary>
        /// 员工批量软删除的接口
        /// </summary>
        /// <param name="ids">被删除的员工id集合</param>
        /// <returns></returns>
        public bool DeleteStaffInfo(List<string> ids)
        {
            foreach (var id in ids)
            {
                //根据员工Id查询用户
                StaffInfo staffInfo = _staffInfoDAL.GetEntityById(id);
                if (staffInfo == null)
                {
                    continue;//跳出本次循环
                }
                staffInfo.IsDalete = true;
                staffInfo.DeleteTime = DateTime.Now;
                //执行修改
                _staffInfoDAL.UpdateEntity(staffInfo);
            }
            return true;
        }
        #endregion

        #region 根据员工的id获取员工的信息（GetStaffInfoById）
        /// <summary>
        /// 根据员工的id获取员工的信息
        /// </summary>
        /// <param name="id">员工的Id</param>
        /// <returns></returns>
        public GetStaffInfoDTO GetStaffInfoById(string id)
        {
            StaffInfo staff = _staffInfoDAL.GetEntityById(id);//先根据id查用户
            if (staff == null)
            {
                return new GetStaffInfoDTO();
            }
            //构建返回数据对象
            GetStaffInfoDTO staffInfo = new GetStaffInfoDTO()
            {
                Id = staff.Id,
                Account = staff.Account,
                StaffName = staff.StaffName,
                DepartmentId = staff.DepartmentId,
                PhoneNum = staff.PhoneNum,
                Sex = staff.Sex == 1 ? "男" : "女",
            };
            return staffInfo;//返回员工信息
        }
        #endregion

        #region 修改员工密码的方法（UpdateStaffPwd）
        /// <summary>
        /// 更新员工信息
        /// </summary>
        /// <param name="id">员工id</param>
        /// <param name="oldPwd">旧的密码</param>
        /// <param name="newPwd">新的密码</param>
        /// <param name="againPwd">确认密码</param>
        /// <param name="msg">返回的消息</param>
        /// <returns></returns>
        public bool UpdateStaffPwd(string id, string oldPwd, string newPwd, string againPwd, out string msg)
        {
            //非空判断
            if (string.IsNullOrWhiteSpace(id))
            {
                msg = "用户的id不能为空！";
                return false;
            }
            if (string.IsNullOrWhiteSpace(oldPwd))
            {
                msg = "原密码不能为空！";
                return false;
            }
            if (string.IsNullOrWhiteSpace(newPwd))
            {
                msg = "新密码不能为空！";
                return false;
            }
            if (newPwd != againPwd)
            {
                msg = "确认密码与新密码一致！";
                return false;
            }
            //查找员工
            StaffInfo staffInfo = _staffInfoDAL.GetEntityById(id);
            if (staffInfo == null)
            {
                msg = "用户不存在！";
                return false;
            }
            //加密
            oldPwd = MD5Helper.GenerateMD5(oldPwd);
            if (staffInfo.PassWord != oldPwd)
            {
                msg = "您输入的原密码有误！";
                return false;
            }
            staffInfo.PassWord = MD5Helper.GenerateMD5(newPwd);//赋值加密后的新密码给员工
            bool isOk = _staffInfoDAL.UpdateEntity(staffInfo);//更新员工信息
            msg = isOk ? "修改密码成功！" : "修改密码失败！";
            return isOk;
        }
        #endregion
    }
}
